import {
  Args,
  Mutation,
  Query,
  Resolver,
  ResolveProperty,
  Parent,
} from '@nestjs/graphql';
import bcrypt from 'bcrypt';

import { UpdateUserDTO } from './dto/update-user.dto';
import { CreateUserDTO } from './dto/create-user.dto';
import { prisma } from '../../generated/prisma-client/blog';
import { QueryDTO } from 'src/common/dto/query.dto';
import { QueryPipe } from 'src/common/pipe/query.pipe';
import { UserInputError } from 'apollo-server';

@Resolver('User')
export class UserResolver {
  @Query('users')
  async users(@Args('query', QueryPipe) { first, skip, orderBy }: QueryDTO) {
    const items = await prisma.users({
      first,
      skip,
      orderBy,
    });
    const count: number = await prisma
      .usersConnection()
      .aggregate()
      .count();

    const count2: number = await prisma
      .usersConnection({
        where: { followings_some: { id: 'ck552k985005f0704p71xl49v' } },
      })
      .aggregate()
      .count();
    console.log(count2);
    return { items, count };
  }

  @ResolveProperty('posts')
  async posts(@Parent() { id }) {
    return await prisma.posts({ where: { author: { id } } });
  }

  @ResolveProperty('followers')
  async followers(@Parent() { id }) {
    return await prisma.users({ where: { followings_some: { id } } });
  }

  @ResolveProperty('following')
  async following(@Parent() { id }) {
    return await prisma.users({ where: { followers_some: { id } } });
  }

  @Mutation('createUser')
  async createUser(
    @Args('user')
    { followerIds, followingIds, ...data }: CreateUserDTO,
  ) {
    const cryptPass = await bcrypt.hash('123456', 10);
    return await prisma.createUser({
      password: cryptPass,
      ...data,
      followers: {
        connect: followerIds && followerIds.map(id => ({ id })),
      },
      followings: {
        connect: followingIds && followingIds.map(id => ({ id })),
      },
    });
  }

  // @Mutation('updateSysUser')
  // @Authorities('AUTH_SYS_USER_UPDATE')
  // async updateSysUser(
  //   @Args('user')
  //   { id, roleIds, ...data }: UpdateUserDTO,
  // ) {
  //   return await prisma.updateSysUser({
  //     where: { id },
  //     data: {
  //       ...data,
  //       roles: {
  //         set: roleIds.map(item => ({
  //           id: item,
  //         })),
  //       },
  //     },
  //   });
  // }

  // @Mutation('deleteSysUsers')
  // @Authorities('AUTH_SYS_USER_DELETE')
  // async deleteSysUsers(
  //   @Args('ids')
  //   ids: string[],
  // ) {
  //   return await prisma.deleteManySysUsers({ id_in: [...ids] });
  // }
}
